<template>
  <el-row class="bgf">
    <el-col :span="12" :offset="5">
      <!-- model表单的数据 -->
      <!-- rules：校验规则 -->
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        class="demo-form"
      >
        <!-- prop="type"校验 ，v-model="form.type"传值-->
        <el-form-item label="上级分类" prop="pid">
          <el-select v-model="form.pid">
            <el-option label="顶级分类" :value="0"></el-option>
            <el-option
              v-for="(item, index) in cateListOption"
              :key="index"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="catename">
          <el-input v-model="form.catename"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload
            action="#"
            list-type="picture-card"
            :file-list="fileList"
            :auto-upload="false"
            :limit="1"
            :on-change="handleChange"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- <el-upload list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload> -->
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="$route.params.id > 0"
            type="primary"
            @click="submitForm('form')"
            >立即修改</el-button
          >
          <el-button v-else type="success" @click="submitForm('form')"
            >立即添加</el-button
          >
          <el-button @click="resetForm('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import { getCateList } from "../../request";
export default {
  data() {
    return {
      form: {
        // pid: 0,
        // img: "",
        // catename: "",
        // status: 1,
      },
      form: this.transData,
      rules: {
        catename: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 上级分类的下拉菜单
      cateListOption: [],
      fileList: [],
    };
  },
  props: ["transData"],

  created() {
    if (this.transData.img) {
      this.fileList = [{ url: this.$host+this.transData.img }];
    } else {
      this.fileList = [];
    }

    // 获取下拉菜单中的数据
    this.getData();
    // 判断新增还是修改
    if (this.$route.params.id > 0) {
      // 有params说明是修改，发请求
      this.getDataById(this.$route.params.id);
    }
  },
  watch: {
    transData: {
      handler(val1,val2) {
        if (val1.img) {
            this.fileList = [{ url: this.$host+val1.img }];
        } else {
          this.fileList = [];
        }
        this.form = val1;
      },
      deep: true,
    },
  },
  methods: {
    // 获取下拉菜单中的数据
    async getData() {
      let res = await getCateList();
      this.cateListOption = res.data.list;
    },

    // 先验证，通过后发请求
    submitForm(formName) {
      // this.$refs[formName]通过refs找到这个表单，然后验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 声明一个formData类型的数据
          let formData = new FormData();
          for (let key in this.form) {
            console.log(this.form[key]);
            formData.append(key, this.form[key]);

            // console.log(formData);
          }
          // 成功之后发请求
          if (this.$route.params.id > 0) {
            this.form.id = this.$route.params.id;
            // 修改
            this.http
              .post("/cateedit", this.form)
              .then((res) => {
                console.log(res);
                // 添加成功后返回列表页
                this.$router.go(-1);
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            // 新增

            // for(let key in formData) {
            //   console.log(formData[key]);
            // }
            this.http
              .post("/cateadd", formData)
              .then((res) => {
                console.log(res);
              })
              .catch((err) => {
                console.log(err);
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 文件上传-修改文件
    handleChange(file, fileList) {
      // 当文件变化时，将最终的值传给img
      console.log(file, fileList);
      this.form.img = file.raw;
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
